<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="clearInput"
            v-model="params.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchClick"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :stripe="true" border :data="userlist" style="width: 100%">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="changestatus(scope.row)"
              v-model="scope.row.mg_state"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作模块 -->
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editClick(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              @click="deleteUser(scope.row.id)"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 头部区域 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      @close="resetForm"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <!-- 主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户信息弹出框 -->
    <el-dialog
      @close="editClose"
      title="修改用户信息"
      :visible.sync="editDialog"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editRuleRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserOk(editForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配角色的弹出框 -->
    <el-dialog
      title="更改用户角色"
      :visible.sync="assignDialogShow"
      width="50%"
    >
      <p>当前的用户:{{assigninfo.username}}</p>
      <p>当前的角色:{{assigninfo.role_name}}</p>
      请选择您要分配的角色：<el-select v-model="value" placeholder="请选择">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="assignRoleOk"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 验证手机号规则
    var checkTel = (rule, value, cb) => {
      const regTel =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regTel.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      userlist: [],
      params: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 2,
      },
      total: 0,
      // 是否弹出添加用户的弹出框控制
      dialogVisible: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkTel, trigger: "blur" },
        ],
      },
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editDialog: false,
      editForm: {},
      assignDialogShow:false,
      // 获取所有角色列表
      roleList:[],
      // 获取当前分配角色的姓名和角色
      assigninfo:{
        username:'',
        role_name:'',
        id:''
      },
      value:''
    };
  },
  created() {
    this.getuserdata();
  },
  methods: {
    async getuserdata() {
      const { data: res } = await this.$http.get("users", {
        params: this.params,
      });
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.userlist = res.data.users;
      // console.log(res);
      // console.log(this.userlist);
      this.total = res.data.total;
      // console.log(this.total);
    },
    handleSizeChange(newsize) {
      console.log(newsize);
      this.params.pagesize = newsize;
      this.getuserdata();
    },
    handleCurrentChange(newNum) {
      this.params.pagenum = newNum;
      this.getuserdata();
    },
    async changestatus(info) {
      // console.log(info);
      const { data: res } = await this.$http.put(
        `users/${info.id}/state/${info.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        // console.log(info.status);
        info.mg_state = !info.mg_state;
        this.$message.error("修改状态失败");
      } else {
        this.$message.success("修改状态成功");
      }
    },
    searchClick() {
      this.getuserdata();
    },
    clearInput() {
      this.params.query = "";
      this.getuserdata();
    },
    // 重置表单
    resetForm() {
      this.$refs.ruleFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      // dialogVisible = false
      this.$refs.ruleFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        else {
          // console.log('添加成功');
          const { data: res } = await this.$http.post("users", this.ruleForm);
          console.log(res);
          if (res.meta.status !== 201) {
            this.$message.error("添加用户失败");
          } else {
            this.$message.success("添加用户成功");
            this.getuserdata();
            this.dialogVisible = false;
          }
        }
      });
    },
    // 编辑用户信息
    async editClick(id) {
      this.editDialog = true;
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("获取用户信息失败");
      // this.$message.success('获取用户信息成功')
      this.editForm = res.data;
      // console.log(this.editForm);
    },
    editClose() {
      this.$refs.editRuleRef.resetFields();
    },
    async editUserOk(id) {
      const { data: res } = await this.$http.put("users/" + id, this.editForm);
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("编辑用户信息失败");
      else {
        this.$message.success("修改用户信息成功");
        this.getuserdata();
        this.editDialog = false;
      }
    },
    async deleteUser(id) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "删除用户提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((result) => result);
      if (result !== "confirm") return this.$message.info("您取消了删除用户");
      else {
        const { data: res } = await this.$http.delete("users/" + id, {
          params: id,
        });
        if (res.meta.status !== 200) return this.$message.error("删除失败");
        else {
          this.$message.success("删除用户成功");
          this.getuserdata();
        }
      }
    },
    async assignRole(info){
      this.assignDialogShow=true
      const {data:res}=await this.$http.get('roles')
      // console.log(res);
      // console.log(info);
      this.roleList=res.data
      this.assigninfo.username=info.username
      this.assigninfo.role_name=info.role_name
      this.assigninfo.id=info.id

    },
    async assignRoleOk(){
      const {data:res}=await this.$http.put('users/'+this.assigninfo.id+'/role',{rid:this.roleList.id})
      // 
      console.log(res);
      if(res.meta.status!==200) return this.$message.error('分配角色失败')
      else{
        this.$message.success('分配角色成功')
        this.assignDialogShow = false
      }
    }
  },
};
</script>

<style scoped>
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>